package ajax;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.CurrentProcess;

import models.DomainModel;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import com.google.gson.Gson;

import entities.Domain;

public class CheckProcess extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		int status = 0;
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (name == null || name.isEmpty() || !UrlHelper.checkDomain(name)) {
			status = 0;
		} else {
			ArrayList<String> processDomains = CurrentProcess.getDomains();
			
			DomainModel domanModel = DomainModel.getInstance();
			Domain domain = domanModel.get(name);
			
			if (domain == null && !processDomains.contains(name)) {
				//Get data
				domain = new Domain();
				domain.setProcessing(true);
				domain.setDomain(name);
				
				Queue queue = QueueFactory.getDefaultQueue();
				queue.add(TaskOptions.Builder.withUrl("/queue-process-domain/" + name).method(Method.GET));
				
				CurrentProcess.insert(name);
				processDomains = CurrentProcess.getDomains();
			}
			
			if (domain != null && !processDomains.contains(name) && !domain.isProcessing()) {
				status = 1;
			}
		}
		
		String json = new Gson().toJson(status);
		response.setContentType("application/json");
		response.getWriter().write(json);
	}
}

